﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UL360SurveyService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new SurveyService() 
            };

            //If run as service
            if (!Environment.UserInteractive)
            {
                ServiceBase.Run(ServicesToRun);
            }
            //If exe is started, applications needs to be built as console application, default is windows application
            else
            {
                //Start service application
                MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
                BindingFlags.Instance | BindingFlags.NonPublic);
                foreach (ServiceBase service in ServicesToRun)
                {
                    onStartMethod.Invoke(service, new object[] { new string[] { } });
                }

                //Wait for user input to shutdown service application
                Console.WriteLine("Press any key to stop the services and end the process...");
                Console.ReadKey();
                
                //Stop service application
                MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
                BindingFlags.Instance | BindingFlags.NonPublic);
                foreach (ServiceBase service in ServicesToRun)
                {
                    Console.Write("Stopping {0}...", service.ServiceName);
                    onStopMethod.Invoke(service, null);
                    Console.WriteLine("Stopped");
                }
            }
        }
    }
}
